package com.foreveross.mofang.datapersistence.web.controller.listener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.mofang.datapersistence.infra.Constant;
import com.foreveross.mofang.datapersistence.infra.IHbaseRepository;
import com.foreveross.mofang.datapersistence.infra.utils.CacheUtils;
import com.foreveross.mofang.datapersistence.infra.utils.PropertiesUtil;

/**
 * 数据脚本初始化
 * 
 * @author fb
 */
public class HbaseDBScriptInit {
	
	private Logger logger = LoggerFactory.getLogger(HbaseDBScriptInit.class);
	
	private IHbaseRepository hbaseRepository;
	
	public HbaseDBScriptInit(IHbaseRepository hbaseRepository) {
		this.hbaseRepository = hbaseRepository;
	}
	
	public void init() {
		logger.info("############################################################");
		logger.info("#正在读取hbase脚本配制文件，准备初始化数据库!");
		
		Properties sysPro = PropertiesUtil.getProperties(Constant.PROPERTIES_HBASE_SCRIPT, CacheUtils.CacheInstance.SYSTEM);
		List<String> familys = new ArrayList<String>();
		String table = null;
		
		try {
			for (Entry<Object, Object> entry : sysPro.entrySet()) {
				table = entry.getKey().toString().toUpperCase();
				
				logger.info("#正在创建hbase数据库表{}!", table);
				
				if (StringUtils.isBlank((String) entry.getValue())) {
					logger.warn("#数据表{}的簇信息为空，系统将跳过此表初始化!", table);
					continue;
				}

				familys.clear();

				for (String family : entry.getValue().toString().split(",")) {
					familys.add(family.trim());
				}

				hbaseRepository.createTable(table, familys);
			}
		} catch (Exception e) {
			logger.error("#hbase数据库初始化出错,系统即将即出！", e);
			System.exit(0);
		}
		
		logger.info("#hbase脚本配制文件己初始化数据库完成!");
		logger.info("############################################################");
	}
}
